package com.shenw.common.card;

import java.io.File;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class CardFactory {
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	protected Card[] build() throws Exception {
		
		Card[] output;
		HashMap<String, String> mapping = new HashMap<String, String>();
		
		File file = new File("src/main/resources/data.xml");
		SAXReader reader = new SAXReader();
		Element root = reader.read(file).getRootElement();
		/*
		 * mapping
		 */
		Element element = root.element("mapping");
		Iterator<Element> iter = element.elementIterator();
		Element subElem;
		while (iter.hasNext()) {
			subElem = iter.next();
			mapping.put(subElem.getName(), subElem.attribute("class").getValue());
		}
		/*
		 * cards
		 */
		element = root.element("package");
		List<Element> cardElem = element.elements("card");
		String suits;
		String value;
		output = new Card[cardElem.size()];
		int i = 0;
		for (Element card : cardElem) {
			suits = card.attributeValue("suits");
			value = card.attributeValue("point");

			Constructor constructor = Class.forName(mapping.get(card.getText())).getConstructor(String.class, String.class);
			output[i++] = (Card) constructor.newInstance(suits, value);
		}
		
		return output;
	}
}
